<script lang="ts">
import { defineComponent, ref, reactive, watch, watchEffect, onUnmounted } from "vue"
import { useI18n } from "vue-i18n";
import { UserModule } from "@/store/modules/user";
import { showToast, showDialog, showConfirmDialog } from 'vant';
import { getAssetsFile } from "@/utils/pub-use";
import { getUserInfo, getMyNFT, openBlindBox, synthesis, mintHF, stopMintHF, cancelSellNFT } from "@/api";
import { NFTList } from "@/utils/nft"
import MyNFTRecord from "@/components/MyNFTRecord.vue";

export default defineComponent({
    components: { MyNFTRecord },
    setup() {
        const { t } = useI18n();
        const pageLoading = ref(true)
        const userInfo = ref({})
        const openBlindBoxIndex = ref(0)
        const synthesisIndex = ref(0)
        const amount = ref(100)
        const setat = reactive({
            pageNum: 0,
            pageSize: 20,
        });
        const refreshing = ref(false);
        const loading = ref(true);
        const finished = ref(false);
        const list = ref([]);
        const onLoad = async () => {
            const res = await getMyNFT(setat);
            if (refreshing.value) {
                list.value = [];
                refreshing.value = false;
            }
            list.value = list.value.concat(res.data.data.NFTList || []);
            loading.value = false;
            setat.pageNum++;
            if (list.value.length >= res.data.data.Total) {
                finished.value = true;
            }
        };
        const onRefresh = () => {
            setat.pageNum = 0;
            finished.value = false;
            loading.value = true;
            refreshing.value = true
            onLoad();
        };
        const sendOpenBlindBox = async () => {
            showConfirmDialog({
                title: t('layout.openblind'),
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {
                            if (userInfo.value.NFTV < Number(amount.value)) {
                                showToast(t("layout.theBalanceNFTVIsOnly") + userInfo.value.NFTV);
                                return;
                            }
                            await UserModule.verifyToken();
                            const res = await openBlindBox({ amount: 1 })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                            } else {
                                showToast(res.data.message)
                            }
                            loadData()
                            onRefresh();
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }
        const sendSynthesis = async () => {
            showConfirmDialog({
                title: t('layout.synthesis'),
                message: t('layout.Thesame4fragmentsarecombinedintoaminingmachine'),
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {
                            await UserModule.verifyToken();
                            const res = await synthesis({ amount: synthesisIndex.value })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                                onRefresh();
                            } else {
                                showToast(t('layout.Notenoughfragments'))
                            }
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }
        const sendMintHF = async (id) => {
            showConfirmDialog({
                title: t('layout.Stakingmining'),
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {

                            await UserModule.verifyToken();
                            const res = await mintHF({ id })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                            } else {
                                showToast(res.data.message)
                            }
                            onRefresh();
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }
        const sendStopMintHF = async (id) => {
            showConfirmDialog({
                title: t('layout.Cancelmining'),
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {
                            await UserModule.verifyToken();
                            const res = await stopMintHF({ id })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                            } else {
                                showToast(res.data.message)
                            }
                            onRefresh();
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }

        const sendCancelSellNFT = async (id) => {
            showConfirmDialog({
                title: t('layout.Cancelsale'),
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {
                            await UserModule.verifyToken();
                            const res = await cancelSellNFT({ id })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                            } else {
                                showToast(res.data.message)
                            }
                            onRefresh();
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }

        const loadData = async () => {
            pageLoading.value = true
            userInfo.value = (await getUserInfo()).data.data.UserInfo || {}
            pageLoading.value = false
        }
        const timer = ref();
        watchEffect(() => {
            timer.value = setInterval(async () => {
                userInfo.value = (await getUserInfo()).data.data.UserInfo || {}
            }, 1500);
        });
        onUnmounted(() => {
            clearInterval(timer.value);
        });
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    loadData();
                    onRefresh();
                }
            },
            { immediate: true }
        );
        return {
            NFTList,
            openBlindBoxIndex,
            synthesisIndex,
            pageLoading,
            userInfo,
            amount,
            list,
            refreshing,
            loading,
            finished,
            loadData,
            onLoad,
            onRefresh,
            sendOpenBlindBox,
            sendSynthesis,
            sendMintHF,
            sendStopMintHF,
            sendCancelSellNFT
        }
    }
})
</script>

<template>
    <div class="page">
        <div class="blindBox">
            <div class="row" :style="`background-image: url(${NFTList[openBlindBoxIndex].image})`">
                <div class="NFTV">
                    {{ $t('layout.Contribution') }}
                    <p>{{ userInfo.NFTV || 0 }}</p>
                </div>
                <div class="cell-button">
                    <template v-for="(item, index) in NFTList">
                        <span v-if="index < 4" :key="index" :class="{ action: openBlindBoxIndex == index }"
                            @click="openBlindBoxIndex = index">{{ $t(`layout.${item.name}`)
                            }}</span>
                    </template>
                </div>
                <van-button type="primary" @click="sendOpenBlindBox" :disabled="pageLoading">{{ amount
                }}{{ $t('layout.Contributionvaluetoopenblindbox') }}</van-button>
            </div>
        </div>
        <div class="synthesis">
            <ul>
                <template v-for="(item, index) in NFTList">
                    <li v-if="index > 3" :key="index" @click="synthesisIndex = (index - 4)">
                        <img :src="item.image" alt="">
                        <div>
                            <div class="label" :class="{ action: synthesisIndex == (index - 4) }">
                                {{ $t(`layout.${item.name}`) }}</div>
                        </div>
                    </li>
                </template>
            </ul>
            <van-button type="primary" @click="sendSynthesis" :disabled="pageLoading">{{ $t('layout.synthesis')
            }}</van-button>
        </div>
        <div class="may-nft">
            <div class="title">{{ $t('layout.MyNFT') }}<img src="@/assets/image/image6.png"
                    @click="$refs.recordRefs.onRefresh()"></div>
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                <van-list v-model:loading="loading" :finished="finished" :finished-text="$t('layout.noMore')"
                    @load="onLoad">
                    <div class="list">
                        <ul>
                            <li v-for="(item, index) in  list " :key="index">
                                <div class="block">
                                    <div class="name"><i></i> <span>{{ $t(`layout.${NFTList[item.NFTType].name}`) }}</span>
                                    </div>
                                    <img :src="NFTList[item.NFTType].image">
                                    <div class="info">
                                        <van-button type="primary" @click="sendMintHF(item.Id)"
                                            v-if="item.Status == 0 || item.Status == 2">{{ $t('layout.Stakingmining')
                                            }}</van-button>
                                        <van-button type="primary" @click="sendStopMintHF(item.Id)"
                                            v-else-if="item.Status == 1">{{ $t('layout.Cancelmining') }}</van-button>
                                        <van-button type="primary" v-else-if="item.Status == 3">{{ $t('layout.Forsale')
                                        }}</van-button>
                                        <div class="HF">
                                            {{ $t('layout.dug') }}{{ item.HF }}
                                        </div>
                                    </div>
                                </div>
                                <div class="foot">
                                    <van-button @click="$refs.sellRefs.show(item.Id)" :disabled="item.Status != 0">{{
                                        $t('layout.sell') }}</van-button>
                                    <van-button @click="sendCancelSellNFT(item.Id)" :disabled="item.Status != 3">{{
                                        $t('layout.Cancelsale') }}</van-button>
                                    <van-button @click="$refs.nftRefs.show(item.Id)"
                                        :disabled="item.Status == 3 || item.Status == 1">{{
                                            $t('layout.transfer') }}</van-button>
                                </div>
                            </li>
                        </ul>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
    </div>
    <transfer-n-f-t ref="nftRefs" @load="onRefresh" />
    <sell-n-f-t ref="sellRefs" @load="onRefresh" />
    <my-n-f-t-record ref="recordRefs" />
</template>

<style lang="less" scoped>
.page {
    padding: 0 15px 15px 15px;

    .blindBox {

        height: 219px;
        padding: 10px 12px;
        box-sizing: border-box;
        background: linear-gradient(41deg, rgba(11, 166, 98, 0) 0%, rgba(11, 166, 98, 0.3) 100%);
        border-radius: 8px;
        border: 4px solid rgba(255, 255, 255, 1);

        .row {
            background-position: top right;
            background-size: 183px 165px;
            background-repeat: no-repeat;

            .NFTV {
                padding-top: 16px;
                color: #1F2120;

                p {
                    margin-top: 8px;
                    font-size: 30px;
                    font-weight: bold;
                    color: #0BA662;
                }
            }

            .cell-button {
                padding: 26px 0 16px 0;
                display: flex;
                justify-content: space-between;

                span {
                    width: 72px;
                    height: 40px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                    font-weight: 500;
                    color: #0BA662;
                    background: #FFFFFF;
                    border-radius: 6px;

                    &.action {
                        background: #d2ece0;
                        border-radius: 6px;
                        border: 1px solid #0BA662;
                        box-sizing: border-box;
                    }
                }
            }
        }
    }

    .synthesis {
        margin-top: 10px;
        height: 159px;
        background: linear-gradient(360deg, rgba(11, 166, 98, 0) 0%, rgba(11, 166, 98, 0.3) 100%);
        border-radius: 8px;
        border: 4px solid rgba(255, 255, 255, 1);

        ul {
            display: flex;
            align-items: center;
            justify-content: space-between;

            li {
                flex: 1;
                padding: 19px 0;
                text-align: center;
                border-right: 1px solid rgba(11, 166, 98, .1);

                img {
                    height: 30px;
                }

                .label {
                    display: inline-block;
                    margin-top: 8px;
                    min-width: 48px;
                    height: 25px;
                    line-height: 25px;
                    text-align: center;
                    background: #FFFFFF;
                    border-radius: 6px;

                    &.action {
                        color: #FFFFFF;
                        background: #0BA662;
                    }
                }

                &:last-child {
                    border: none;
                }
            }
        }

        .van-button {
            width: 313px;
            display: block;
            margin: 0 auto;
        }
    }

    .may-nft {
        margin-top: 20px;

        .title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 15px;
            font-weight: bold;
            color: #1F2120;

            img {
                width: 15px;
                height: 15px;
            }
        }

        .list {
            margin-top: 12px;

            ul {
                li {
                    margin-bottom: 10px;
                    background: rgba(11, 166, 98, 0.05);
                    border-radius: 8px;
                    border: 1px solid #FFFFFF;

                    .block {
                        padding: 13px 18px 0 18px;
                        position: relative;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .name {
                            position: absolute;
                            left: 0;
                            top: 0;
                            display: flex;
                            align-items: center;
                            width: 98px;
                            height: 28px;
                            background: rgba(255, 255, 255, 0.6);
                            border-radius: 6px 0px 50px 0px;
                            border: 1px solid #FFFFFF;

                            i {
                                display: inline-block;
                                width: 6px;
                                height: 6px;
                                margin: 0 8px 0 10px;
                                border: 2px solid #0BA662;
                                box-sizing: border-box;
                                border-radius: 50%;
                            }
                        }

                        img {
                            position: relative;
                            height: 135px;
                            z-index: 2;
                        }

                        .info {
                            text-align: center;
                            align-items: center;

                            .HF {
                                margin-top: 8px;
                                font-size: 12px;
                                font-weight: 400;
                                color: #0BA662;
                            }

                            .van-button {
                                height: 33px;
                                font-size: 12px;
                                min-width: 108px;
                            }
                        }
                    }

                    .foot {
                        display: flex;
                        justify-content: space-between;
                        padding: 17px 0;
                        background: #FFFFFF;

                        .van-button {
                            flex: 1;
                            height: 14px;
                            font-size: 12px;
                            border: none;
                            border-right: 1px solid rgba(11, 166, 98, 0.2);
                            border-radius: 0;

                            &:last-child {
                                border: none;
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>
